import { DownOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, Tooltip, Tabs, Card, Switch } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { TableListItem } from './data';
import router from "umi/router";
import { queryRule, updateRule, addRule, removeRule } from './service';
import { selectEnum } from '@/utils/utils';
import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
interface TableListProps extends FormComponentProps { }
const { TabPane } = Tabs;

const TableList: React.FC<TableListProps> = props => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({ common: {} });
    const [type, setType] = useState<any>(3);
    const [nameList, setnameList] = useState<any>([]);
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    const [content, setcontent] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);

    const actionRef = useRef<ActionType>();

    const handleName = (val) => {
        setnameList(val)
    }
    const getTabKey = () => {
        const url = '/operation/content-group';
        const tabKey = location.pathname.replace(`${url}/`, '');
        if (tabKey && tabKey !== '/') {
            return tabKey;
        }
        return 'all';
    };
    const handleTabChange = (key: string) => {
        const url = '/operation/content-group';
        switch (key) {
            case 'all':
                router.push(`${url}/all`);
                break;
            case 'recommend':
                router.push(`${url}/recommend`);
                break
            case 'stop':
                router.push(`${url}/stop`);
                break;
            default:
                break;
        }
    };
    const tabList = [
        {
            key: 'all',
            tab: '全部小组',
        },
        {
            key: 'recommend',
            tab: '推荐小组',
        },
        {
            key: 'stop',
            tab: '停用小组',
        },
    ];
  
    

    // 请求接口数据, 设置组件状态
    const getTableData = (params: any) => {
        params.type = type;
        return queryRule(params).then((res: any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }
    const callback = (key) => {
        console.log(key);
        setType(key)
        //getTableData({type:key})
    }
    const { children } = props;
    // 表单提交
    const handleSubmitDataForm = (value: any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }


    return (
        <PageHeaderWrapper
            content="使用小组可以实现 BBS 版区、社群圈子、内容分类等各种运营场景。"
            tabList={tabList}
            tabActiveKey={getTabKey()}
            onTabChange={handleTabChange}>
                {children}
        

            {/* <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={apiState.common || {}}
                selectType={type}
                handleName={handleName}
                nameList={nameList}
                onSubmit={async formValue => handleSubmitDataForm(formValue)}
                onCancel={() => handleDataModalVisible(false)}
            /> */}
            {
                previewModelVisible && (
                    <PreviewForm
                        previewModelVisible={previewModelVisible}
                        onVisibleModel={handlePreviewModalVisible}
                        previewImg={previewImg}
                    />
                )
            }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids: any = selectedRows.map(row => row.id).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: { ids },
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};

const handleUpdateItem = async (fields: FormValueType) => {
    return RequestHelper.bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};
export default Form.create<TableListProps>()(TableList);
